<?php

class Quad_Router_HttpPretty extends Quad_Router_Abstract {
	
	protected $_get;
	public $url;
	
  public function __construct(Quad_Bootstrap_Interface $bootstrap) {
    $this->_bootstrap = $bootstrap;    
		$this->url = $this->_bootstrap->url;
		$this->_get = $_GET;
		$this->_parseUrl();     
	}
	
	protected function _parseUrl() {
    $this->url = str_replace('/quad', '', $this->url);
    $url = rawurldecode($this->url);
		$parts = explode('/', trim($url, '/'));
    $this->_controllerName = $parts[0] ? array_shift($parts) : 'index';
    $this->_actionName = count($parts) > 0 && $parts[0] ? array_shift($parts) : 'index'; 
	  foreach ($parts as $i => $part) {
      if (($i % 2) == 0) {
        // even
        $field = $part;
        if (strlen($field)) {
          if (preg_match('/\[([\w_-]*)\]$/', $field, $match)) {
            if ($match[1]) {
              $akey = $match[1];
            }
            $this->_get[$field] = array();
            
          } elseif (isset($this->_get[$field])) {
            $this->_get[$field] = array($this->_get[$field]);
          }
        }
      } else {
        // odd
        $rawValue = $part;
        if ($field) {
          if (is_array($this->_get[$field])) {
            if ($akey) {
              $this->_get[$field][$akey] = $rawValue;
              $akey = null;
              
            } else {
              $this->_get[$field][] = $rawValue;
            }
          } else {
            $this->_get[$field] = $rawValue;
          }
        }
      }
    }		
	}
	
  public function redirect($url, $getParams = array()) {
    if (!preg_match('~^[a-z+]+://~', $url)) {
      $url = HTTP_ROOT . "/$url";
    }
    if (count($getParams)) {
      $url = $this->_expandParams($url, $getParams);
    }
    $url = rawurlencode(HTTP_ROOT . $url);
    header("Location: $url");
    exit(0);
  }	
	
	public function redirectDouble($url, $getParams) {
		
	}
  
  protected function _expandParams($url, $getParams) {
    foreach ($getParams as $key => $value) {
      if (is_array($value)) {
        $i = 0;
        foreach ($value as $k => $v) {
          if ($k === $i++) {
            $url .= "/{$key}[]/$v";
          } else {
            $url .= "/{$key}[{$k}]/$v";
          }
        }
      } else {
        $url .= "/$key/$value";
      }
    }
    return $url;  	
  } 
	
  public function buildUrl($controller = 'index', $action = 'index', $params = array(), $fragment = '') {
    $url = "$controller/$action";
    if (count($params)) {
      $url = $this->_expandParams($url, $params);
    }
    $fragment = ($fragment ? "#$fragment" : '');
    return HTTP_ROOT . $url; 
  }	
	
}